package com.lry.mqstarter.extend;

import com.alibaba.fastjson.JSON;
import com.lry.producer.DefaultMqProducer;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.*;
import org.springframework.boot.context.properties.bind.BindResult;
import org.springframework.boot.context.properties.bind.Binder;
import org.springframework.context.EnvironmentAware;
import org.springframework.core.env.Environment;
import com.lry.mqstarter.build.ProducerBuild;
import com.lry.mqstarter.properties.MqProducerDetailProperties;
import com.lry.mqstarter.properties.MqProducerProperties;

import java.util.Map;

@Slf4j
public class MqProducerRegistryPostProcessor implements BeanDefinitionRegistryPostProcessor, EnvironmentAware {

    private Environment environment;

    //自建mq 配置文件前缀
    private static final String SELF_CORE_URL_PREFIX = "rocketmq.self.producer";


    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {

        BindResult<MqProducerProperties> restServiceBindResult = Binder.get(environment).bind(SELF_CORE_URL_PREFIX, MqProducerProperties.class);
        if (restServiceBindResult == null || !restServiceBindResult.isBound()) {
            return;
        }
        MqProducerProperties mqProducerProperties = restServiceBindResult.get();

        MqProducerDetailProperties defaultProp = mqProducerProperties.getDefaultProp();
        Map<String, MqProducerDetailProperties> producersMap = mqProducerProperties.getProducers();

        log.info("初始化mq生产者配置-defaultProp--------{}", JSON.toJSONString(defaultProp));

        for (String str : producersMap.keySet()) {
            MqProducerDetailProperties properties = producersMap.get(str);

            String beanName = str;
            if (StringUtils.isNotBlank(properties.getBeanName())) {
                beanName = properties.getBeanName();
            }
            log.info("MQ，beanName:{}生产端开始注册,{} ", beanName, JSON.toJSONString(properties));

            //生成rocketmq生产对象
            DefaultMqProducer defaultMQProducer = ProducerBuild.buildSelfMQProducer(properties, defaultProp);
            if(null==defaultMQProducer){
                log.error("启动self mq生产者错误：beanName={}",beanName);
                continue;
            }
            beanFactory.registerSingleton(beanName, defaultMQProducer);
        }
    }

    @Override
    public void setEnvironment(Environment environment) {
        this.environment = environment;
    }

    @Override
    public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {

    }
}
